package com.oz;

import java.io.File;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.util.regex.Matcher;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

	java.util.logging.Logger log = java.util.logging.Logger.getLogger(this.getClass().getName());

	@Value("${spring.jpa.properties.upload-path:UPFILES}")
	private String UPLOADPATH;

	@Value("${spring.jpa.properties.resource-path:}")
	public String resourcePath;

	/**
	 * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor =
	 * false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
	 */
	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
		return interceptor;
	}

	/**
	 * 存储路径复制 首页图片路径写入常量 数据路径赋值
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		try {

			// 存储路径赋值
			Utils.UPLOADPATH = (ResourceUtils.getURL("").getPath() + '/' + StringUtils.trimAllWhitespace(UPLOADPATH)
					+ '/');
			Utils.UPLOADPATH = Utils.UPLOADPATH.replaceAll("(/+)|(\\+)", Matcher.quoteReplacement(File.separator));
			if (!new File(Utils.UPLOADPATH).exists())
				new File(Utils.UPLOADPATH).mkdir();

			// 静态文件路径，区别于部分静态文件使用 upload
			resourcePath = StringUtils.trimAllWhitespace(resourcePath).replaceAll("^\\/*", "/").replaceAll("\\/$", "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		registry.addResourceHandler(resourcePath + "/**").addResourceLocations("file:" + Utils.UPLOADPATH).setCacheControl(CacheControl.maxAge(Duration.ofDays(true ? 365 : 0)));
		log.info("-------成功映射路径 ---<<<<<< " + resourcePath + "/** 到: " + Utils.UPLOADPATH);

//		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/").setCacheControl(CacheControl.maxAge(Duration.ofDays(cache ? 15 : 0)));
//		log.info("-------------------------DASHBOARD --->>>" + "file:" + JSON.toJSONString(Utils.DASHBOARD, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteNullStringAsEmpty));
	}

}
